using AutoMapper;
using B.S.NewMedical.Api.Write.Application.Command.User;
using B.S.NewMedical.Domain.User;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;

namespace B.S.NewMedical.Api.Write.Application.Handler.User
{
    /// <summary>
    /// 创建用户处理器
    /// </summary>
    public class CreateUserHandler : IRequestHandler<CreateUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UserModel> _userRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<CreateUserHandler> _logger;

        public CreateUserHandler(
            IBaseRepository<UserModel> userRepository,
            IMapper mapper,
            ILogger<CreateUserHandler> logger)
        {
            _userRepository = userRepository;
            _mapper = mapper;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 参数验证
                if (string.IsNullOrWhiteSpace(request.Username))
                    return new ApiResult<int> { Code = ApiEnum.Fail, Msg = "用户名不能为空" };

                if (string.IsNullOrWhiteSpace(request.RealName))
                    return new ApiResult<int> { Code = ApiEnum.Fail, Msg = "用户真实姓名不能为空" };

                if (string.IsNullOrWhiteSpace(request.UserPassword))
                    return new ApiResult<int> { Code = ApiEnum.Fail, Msg = "用户密码不能为空" };

                // 验证用户类型
                if (request.Type <= 0)
                    return new ApiResult<int> { Code = ApiEnum.Fail, Msg = "请选择用户类型" };

                // 验证用户名是否已存在
                var existingUser = _userRepository.GetAll().FirstOrDefault(u => u.Username == request.Username && !u.IsDeleted);
                if (existingUser != null)
                    return new ApiResult<int> { Code = ApiEnum.Fail, Msg = "用户名已存在" };

                // 使用AutoMapper创建用户实体
                var user = _mapper.Map<UserModel>(request);
                user.CreateTime = DateTime.Now;
                user.CreatePeople = "System"; // 实际项目中应该从当前用户获取

                // 保存用户
                var userId = await _userRepository.CreateAsync(user);

                _logger.LogInformation("成功创建用户，ID：{UserId}", userId);

                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Msg = "创建用户成功",
                    Data = userId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建用户时发生异常");
                return new ApiResult<int>
                {
                    Code = ApiEnum.Error,
                    Msg = "创建用户失败：" + ex.Message
                };
            }
        }
    }
} 